package com.coalmine.iec104.modules.delayed.entity;

import lombok.Data;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Author mkq
 * @Date 2021-11-04 8:52
 * @Description
 */
@Data
public class ItemDelayed<T> implements Delayed {

    /**默认延迟1秒*/
    private final static long DELAY =  1000L;

    /**到期时间*/
    private long expire;
    /**创建时间*/
    private Date now;
    /**泛型data*/
    private T data;

    public ItemDelayed(long startTime, long secondsDelay) {
        super();
        this.expire = startTime + (secondsDelay * 1000);
        this.now = new Date();
    }

    public ItemDelayed(long startTime) {
        super();
        this.expire = startTime + DELAY;
        this.now = new Date();
    }



    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

}
